<template>
  <div class="container">
    <a-card 
     :bordered="false" 
     class="search-card">
     <a-row>
      <a-col :flex="'450px'">
        <a-form
        :model="formModel"
        :label-col-props="{ span: 1 }"
        label-align="left">
        <a-form-item field="createdTime" hide-label>
          <a-range-picker v-model="formModel.createdTime" show-time/>
          <a-button type="primary" @click="onSearch" 
          style="margin-left: 20px">查询</a-button>
        </a-form-item>
      </a-form> 
      </a-col>
     </a-row>   
    </a-card>
    <a-card >
      <div class="grid-demo-background">
    <a-space direction="vertical" :size="16" style="display: block;">
      <a-row class="grid-demo" :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="6" :xs="24" :sm="24" :md="12" :lg="6" >
           <WidrageCard bgName="blue" label="总进件数" :value="leftSideData?.entry_count"/>
        </a-col>
        <a-col :span="6" :xs="24" :sm="24" :md="12" :lg="6" >
          <WidrageCard bgName="orange" label="已获取" :value="leftSideData?.phone_viewed_already"/>
        </a-col>
        <a-col :span="6" :xs="24" :sm="24" :md="12" :lg="6" >
          <WidrageCard bgName="purple" label="未获取" :value="leftSideData?.phone_viewed_not"/>
        </a-col>
        <a-col :span="6" :xs="24" :sm="24" :md="12" :lg="6" >
          <WidrageCard 
            v-if="leftSideData?.balance_display_status == 1"
            v-permission="['admin']" bgName="green" label="余额" 
            :value="leftSideData?.balance"/>
        </a-col>
      </a-row>
      
    </a-space>
  </div>
    </a-card>
    <div class="home-page-layout">
     
    <div class="right-side">
      <!-- 添加顶部间距 -->
      <div style="height: 20px;"></div>
      <a-row :gutter="isMoblie ? [20, 20] : [17,17]">
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
            <ThirtyDaysCount 
            :yAxisData="daysCount?.yAxisData"
            :seriesData="daysCount?.seriesData"/>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12">
             <CluesContactPercent :data="cluePieData"/>
          </a-col>
      </a-row>
      <div class="right-side-bottom-table">
        <CrudTable
          ref="tableRef"
          :showPage="false"
          :columns="columns"
          :scroll="{ y: 400 , x: 750}"
          :fetchData="fetchData"
          @rowClick="tableRowClick">
            <template #entryStatusSlot="{ record }">
              <a-switch v-model="record.entry_status" 
              :checked-value="1" :unchecked-value="0"
              :beforeChange="entryStatusChange"/>
            </template>
        </CrudTable>  
      </div>
    </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { onMounted, reactive, ref, computed, ComputedRef } from 'vue';
import { isUndefined, isNull } from 'lodash';
import WidrageCard from './components/widrageCard.vue';
import { queryDashboardData } from '@/api/dashboard';
import ThirtyDaysCount from './components/thirty-days-count.vue'
import CluesContactPercent from './components/clues-contact-percent.vue'
import { getCurrentDate, getCurrentNextDayDate } from '@/utils/dateUtil';
import { updatePersonStatus } from "@/api/personnel";
import { Message } from '@arco-design/web-vue';
import { useAppStore } from '@/store';

const appStore = useAppStore()
const leftSideSpan = computed(()=>{
   return appStore.device == 'mobile' ? 24 : 8
})

const isMoblie = computed(()=>{
   return appStore.device == 'mobile'
})

const tableRef = ref();
let starTime = getCurrentDate()
let endTime = getCurrentNextDayDate();
let formModel = reactive({
   createdTime: [
     starTime,
     endTime
   ]
});

let daysCount = reactive({
     yAxisData: [],
     seriesData: [],
})
let percentData = ref([])
let tableList = ref<any>();    // 表格数据列
let recentlyData = ref<any>(); // 列表
let cluePieData = ref<any>();  //列表


let phoneViewedAlready = ref<number>(); //已获取手机号
let phoneViewedNot = ref<number>(); //未获取手机号
let balanceDisplayStatus = ref<any>(); // 余额是否显示

const onSearch = ()=>{
  tableRef.value.reloadEvent()
}

const columns = [
  {
    title: '客户经理',
    dataIndex: 'name',
    align: 'center'
  },
  {
    title: '进件数量',
    align: 'center',
    dataIndex: 'total_clue_count',
  },
  {
    title: '已获取',
    dataIndex: 'phone_viewed_already',
    align: 'center',
  },
  {
    title: '未获取',
    dataIndex: 'phone_viewed_not',
    align: 'center',
  },
  {
    title: '接通',
    dataIndex: 'answered_calls',
    align: 'center',
  },
  {
    title: '未接',
    align: 'center',
    dataIndex: 'not_connected',
    
  },
  {
    title: '推送状态',
    align: 'center',
    dataIndex: 'entry_status',
    slotName: 'entryStatusSlot'
  },
];


interface LeftCardData {
  entry_count: number,
  phone_viewed_already: number,
  phone_viewed_not: number,
  balance: number,
  balance_display_status: number
}

let leftSideData = reactive<LeftCardData>({
    entry_count: 0,
    phone_viewed_already: 0,
    phone_viewed_not: 0,
    balance: 0,
    balance_display_status: 0
}) 

let selectItem = ref<any>()
const tableRowClick = (result : any)=>{
  selectItem.value = result
}


const entryStatusChange = async (newValue): Promise<boolean | void>=> {
  return new Promise((resolve, reject) => {
    setTimeout(()=> {
      updatePersonStatus({
          id: selectItem.value?.uid,
          entry_status: newValue
       }).then((res: any)=>{
        if(res.code == 1){
          Message.success("修改成功")
          resolve(true)
        } else {
          reject()
          Message.error("修改失败")
        }
       }).catch(()=>{
          reject()
       })
    }, 300)
  })
}


const fetchData = () : any=>{
  let [ startTime , endTime ] = formModel.createdTime
  if(!isUndefined(startTime) && !isNull(startTime)
    && !isUndefined(endTime) && !isNull(endTime)){
      return queryDashboardData({
        start_time: dayjs(startTime).valueOf() / 1000,
        end_time: dayjs(endTime).valueOf() / 1000
      }).then(({ data }: any)=>{
        if(!isNull(data?.info) && !isUndefined(data?.info)){
          let {
            recently_data,
            clue_pie_data,
            entry_count,
            balance,
            phone_viewed_already,
            phone_viewed_not,
            balance_display_status,
            organization_personnel_list,
          } = data?.info;

          leftSideData.entry_count = entry_count;
          leftSideData.phone_viewed_already = phone_viewed_already;
          leftSideData.phone_viewed_not = phone_viewed_not;
          leftSideData.balance = balance;
          leftSideData.balance_display_status = balance_display_status;

          cluePieData.value = clue_pie_data;
          recentlyData.value = recently_data;
          balanceDisplayStatus.value = balance_display_status;
          phoneViewedNot.value = phone_viewed_not;
          phoneViewedAlready.value = phone_viewed_already;
          tableList.value = organization_personnel_list

          if(Array.isArray(recently_data)){
              daysCount.yAxisData = [];
              daysCount.seriesData = [];
              recently_data.forEach((item)=> {
                daysCount.yAxisData.push(item?.type);
                daysCount.seriesData.push(item?.sales);
             })
          }
          
          return { data: tableList.value, total: 0 }
        }
      })
 } 
 return new Promise((resole)=>{
    resole({})
 })
}

</script>

<style lang="less" scoped>
  .home-page-layout{
    display: flex;
  }

  :deep(.arco-form-item){
    margin-bottom: 0px;
  }

  .search-card{
    margin-bottom: 20px;
    background-color: var(--color-bg-2);
    border-radius: 4px;
    overflow: auto;
  }

  .left-side {
    width: 400px;
    background: #fff;
    padding: 35px 30px;
  }

  .right-side {
    flex: 1;
  }

  .right-side-bottom-table{
    position: relative;
    margin-top: 17px;
    padding: 16px 26px;
    background: var(--color-bg-2);
    transition: box-shadow 0.2s cubic-bezier(0, 0, 1, 1);
  }

</style>

<style lang="less" scoped>
  // 响应式
  .mobile {
    .home-page-layout{
      display: block;
    }
    .container {
      display: block;
    }
    .left-side {
      width: 100%;
      margin-left: 0;
      margin-top: 20px;
    }
    .right-side {
      margin-left: 0;
      margin-top: 20px;
    }
  }
</style>
